// export const baseURL: String = 'http://192.168.1.43:1314'
export const baseURL: String = 'http://47.115.220.79:1314'

// 拦截器配置
const httpInterceptor = {
    // 拦截前触发
    invoke(options: UniApp.RequestOptions) {
        // 1. 非 http 开头需拼接地址
        if (!options.url.startsWith('http')) {
            options.url = baseURL + options.url
        }
        // 2. 请求超时
        options.timeout = 10000
        // 3. 添加小程序端请求头标识
        options.header = {
            'source-client': 'miniapp',
            ...options.header,
        }
        // 4. 添加 token 请求头标识
        const useUserStore = JSON.parse(uni.getStorageSync('useUserStore') || '{}')
        if (useUserStore.token && !options.url.match("/sxg/sxg_user/info")) {
            options.header.Authorization = useUserStore.token
        }
        uni.showLoading({
            title: '加载中...'
        })
    },

    success(args: UniApp.RequestSuccessCallbackResult) {
        let data: any = args.data
        if (typeof args.data == 'string') {
            data = JSON.parse(args.data);
        }
        if (data.code == 10001) {
            uni.showToast({
                title: '登录已过期，请重新登录',
                icon: 'none',
                duration: 2000,
                success: () => {
                    uni.removeStorageSync('useUserStore')
                    uni.reLaunch({
                        url: '/pages/login/login'
                    })
                }
            })
        } else if (data.code == 202) {
            uni.showToast({
                title: "系统异常，请稍后重试",
                icon: 'none',
                duration: 2000
            })
        } else if(data.code != 200) {
            uni.showToast({
                title: data.msg,
                icon: 'none',
                duration: 2000
            })
        }
    },

    fail(err: UniApp.GeneralCallbackResult) {
        uni.showToast({
            title: '网络异常，请稍后重试',
            icon: 'none'
        })
    },


    complete(args: UniApp.ReadCompleteCallback) {
        uni.hideLoading();
    }


}

// 拦截 request 请求
uni.addInterceptor('request', httpInterceptor)
// 拦截 uploadFile 文件上传
uni.addInterceptor('uploadFile', httpInterceptor)